package cn.com.twoke.easyproject.aspect.request.lock;

import cn.com.twoke.easyproject.aspect.request.lock.hook.after.*;
import cn.com.twoke.easyproject.aspect.request.lock.generator.BasicKeyGenerator;
import cn.com.twoke.easyproject.aspect.request.lock.hook.proceed.DistributedJoinPointProceed;
import cn.com.twoke.easyproject.aspect.request.lock.hook.proceed.RequestLockKeyJoinPointProceed;
import cn.hutool.crypto.digest.MD5;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 请求锁配置项
 */
@Configuration
public class RequestLockKeyConfiguration {

    @Bean
    public RequestLockKeyGenerator requestLockKeyGenerateHookManager() {
        return new RequestLockKeyGenerateAfterDecorator(new BasicKeyGenerator())
                .add(new GenerateKeyAfterWithPrefix())
                .add(new GenerateKeyAfterWithUser())
                .add(new GenerateKeyAfterWithRequestPath())
                .add(new GenerateKeyAfterCompressor(key -> MD5.create().digestHex(key.getBytes())))
                ;
    }

    @Bean
    public RequestLockKeyJoinPointProceed requestLockKeyJoinPointProceed(RedissonClient redissonClient) {
        return new DistributedJoinPointProceed(redissonClient);
    }

    @Bean
    @ConditionalOnBean({
            RequestLockKeyGenerator.class,
            RequestLockKeyJoinPointProceed.class
    })
    public RequestLockAspect requestLockAspect(
            RequestLockKeyGenerator requestLockKeyGenerator,
            RequestLockKeyJoinPointProceed requestLockKeyJoinPointProceed) {
        return new RequestLockAspect(requestLockKeyGenerator, requestLockKeyJoinPointProceed);
    }

}
